package com.fw.web.controller.system;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fw.common.IdXD;
import com.fw.constant.Constant;
import com.fw.core.domain.model.LoginUser;
import com.fw.mes.Result;
import com.fw.system.admin.domain.FwAgentRegion;
import com.fw.system.admin.domain.FwImages;
import com.fw.system.admin.domain.FwSku;
import com.fw.system.admin.service.*;
import com.fw.utils.ServletUtils;
import com.fw.utils.StringUtils;
import com.fw.utils.spring.SpringUtils;
import com.fw.web.web.service.TokenService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.fw.annotation.Log;
import com.fw.core.controller.BaseController;
import com.fw.core.domain.AjaxResult;
import com.fw.enums.BusinessType;
import com.fw.system.admin.domain.FwSpu;
import com.fw.utils.poi.ExcelUtil;
import com.fw.core.page.TableDataInfo;

import static com.fw.mes.ResultUtils.success;

/**
 * 商品Controller
 *
 * @author yanwei
 * @date 2021-05-10
 */
@RestController
@RequestMapping("/admin/spu")
public class FwSpuController extends BaseController {
    private final IFwSpuService fwSpuService;
    private final ISysUserService sysUserService;
    private final TokenService tokenService;
    private final IFwRuleDatasService ruleDatasService;
    private final IFwShopService shopService;
    private final IFwSkuService skuService;
    private final IFwImagesService imagesService;
    private final IdXD idXD;
    private final IFwAgentRegionService agentRegionService;

    public FwSpuController(IdXD idXD, IFwImagesService imagesService, IFwSkuService skuService,
                           IFwSpuService fwSpuService, ISysUserService sysUserService, TokenService tokenService,
                           IFwRuleDatasService ruleDatasService, IFwShopService shopService,
                           IFwAgentRegionService agentRegionService) {
        this.fwSpuService = fwSpuService;
        this.sysUserService = sysUserService;
        this.tokenService = tokenService;
        this.ruleDatasService = ruleDatasService;
        this.shopService = shopService;
        this.skuService = skuService;
        this.imagesService = imagesService;
        this.idXD = idXD;
        this.agentRegionService = agentRegionService;
    }
    /**
     * 查询特卖商品列表
     */
    @PreAuthorize("@ss.hasPermi('admin:one_area_item:list')")
    @GetMapping("/areaList")
    public Result<List<FwSpu>> areaList(){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        FwAgentRegion agentRegion = sysUserService.getAgentRegion(loginUser);
        List<FwSpu> fwSpus = fwSpuService.list(Wrappers.<FwSpu>lambdaQuery().eq(FwSpu::getArea,agentRegion.getArea()));
        return success(fwSpus);
    }




    /**
     * 查询商品列表
     */
    @PreAuthorize("@ss.hasPermi('admin:spu:list')")
    @GetMapping("/list")
    public TableDataInfo list(FwSpu fwSpu) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String shopId = sysUserService.isShop(loginUser);
        if (org.apache.commons.lang3.StringUtils.isNotBlank(shopId)){
            fwSpu.setShopId(shopId);
        }
        // 代理
        FwAgentRegion agentRegion = sysUserService.getAgentRegion(loginUser);
        if (Objects.nonNull(agentRegion)){
            fwSpu.setArea(agentRegion.getArea());
        }
        startPage();
        List<FwSpu> list = fwSpuService.list(Wrappers.<FwSpu>lambdaQuery()
                .like(!StringUtils.isEmpty(fwSpu.getTitle()), FwSpu::getTitle, fwSpu.getTitle())
                .eq(StringUtils.isNotEmpty(shopId), FwSpu::getShopId, shopId)
                .eq(fwSpu.getStatus() != null, FwSpu::getStatus, fwSpu.getStatus())
                .eq(!StringUtils.isEmpty(fwSpu.getCategory()), FwSpu::getCategory, fwSpu.getCategory())
                .eq(!StringUtils.isEmpty(fwSpu.getArea()), FwSpu::getArea, fwSpu.getArea())
                .orderByDesc(FwSpu::getUpdateTime));
        list.forEach(spu-> {
            spu.setSkuList(skuService.list(Wrappers.<FwSku>lambdaQuery().eq(FwSku::getSpuId, spu.getId())));
            spu.setImages( imagesService.list(Wrappers.<FwImages>lambdaQuery()
                    .eq(FwImages::getBusinessId, spu.getId())
                    .eq(FwImages::getStatus, 1)) );
        } );
        return getDataTable(list);
    }

    /**
     * 导出商品列表
     */
    @PreAuthorize("@ss.hasPermi('admin:spu:export')")
    @Log(title = "商品", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(FwSpu fwSpu) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String shopId = sysUserService.isShop(loginUser);
        fwSpu.setShopId(shopId);

        List<FwSpu> list = fwSpuService.list(Wrappers.<FwSpu>lambdaQuery()
                .like(!StringUtils.isEmpty(fwSpu.getTitle()), FwSpu::getTitle, fwSpu.getTitle())
                .eq(StringUtils.isNotEmpty(shopId), FwSpu::getShopId, shopId)
                .eq(fwSpu.getStatus() != null, FwSpu::getStatus, fwSpu.getStatus())
                .eq(!StringUtils.isEmpty(fwSpu.getCategory()), FwSpu::getCategory, fwSpu.getCategory()));

        ExcelUtil<FwSpu> util = new ExcelUtil<>(FwSpu.class);
        return util.exportExcel(list, "商品列表");
    }

    /**
     * 获取商品详细信息
     */
    @PreAuthorize("@ss.hasPermi('admin:spu:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        FwSpu spu = fwSpuService.getById(id);
        spu.setSkuList(skuService.list(Wrappers.<FwSku>lambdaQuery().eq(FwSku::getSpuId, spu.getId())));
        spu.setImages( imagesService.list(Wrappers.<FwImages>lambdaQuery()
                .eq(FwImages::getBusinessId, spu.getId())
                .eq(FwImages::getStatus, 1)) );
        return AjaxResult.success(spu);
    }

    /**
     * 新增商品
     */
    @PreAuthorize("@ss.hasPermi('admin:spu:add')")
    @Log(title = "商品", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@RequestBody FwSpu fwSpu) {
            fwSpu.setId(idXD.nextId());
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            String shopId = sysUserService.isShop(loginUser);
            // 代理的逻辑
            if (StringUtils.isBlank(shopId)){
                shopId =  sysUserService.isProxyAndShop(loginUser);
                // 如果是代理 只能添加特卖
                FwAgentRegion agentRegion = sysUserService.getAgentRegion(loginUser);
                if (Objects.nonNull(agentRegion)){
                    Assert.isTrue(Integer.valueOf(1).equals(fwSpu.getIsSale()),"代理只可添加特卖商品!");
                }
            }

            if (StringUtils.isNotBlank(shopId)) {fwSpu.setShopId(shopId);}
            Assert.isTrue(StringUtils.isNotBlank(fwSpu.getShopId()),"商铺未指定不可添加商品,代理请先申请商户!");

        AjaxResult success = updateAndSave(fwSpu);
        if (success != null) {return success;}

        return AjaxResult.success(fwSpuService.save(fwSpu));
    }

    /**
     * 修改商品
     */
    @PreAuthorize("@ss.hasPermi('admin:spu:edit')")
    @Log(title = "商品", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult edit(@RequestBody FwSpu fwSpu) {

        AjaxResult success = updateAndSave(fwSpu);
        if (success != null) {return success;}

        return AjaxResult.success(fwSpuService.updateById(fwSpu));
    }

    private AjaxResult updateAndSave(FwSpu fwSpu) {
        if (fwSpu.getPrice().compareTo(BigDecimal.valueOf(0.01)) < 0) { return AjaxResult.error(1,"让利不可低于0.01"); }
        if (fwSpu.getRealPrice().compareTo(fwSpu.getPrice()) < 0) { return AjaxResult.error(1,"当前售价不可低于让利"); }
        BigDecimal divide = fwSpu.getPrice().divide(fwSpu.getRealPrice(), 3, BigDecimal.ROUND_HALF_EVEN);
        if (fwSpu.getIsQuiz() != null && fwSpu.getIsQuiz() == 1) {
            if ( divide.compareTo(BigDecimal.valueOf(0.35)) < 0) {
                return AjaxResult.error(1,"成为竞猜商品，利润值需大于售价的35%");
            }
        } else {
            //特卖商品不做判断 和线下
            if (Integer.valueOf(0).equals(fwSpu.getIsOffline())){
                if (!Integer.valueOf(1).equals(fwSpu.getIsSale()) && divide.compareTo(BigDecimal.valueOf(0.2)) < 0) {
                    return AjaxResult.error(1,"提交商品，利润值需大于售价的20%");
                }
            }

        }

        //特卖验证
        if (Integer.valueOf(1).equals(fwSpu.getIsSale())) {
            // 获取当前的用户
            LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
            if (loginUser == null) {return AjaxResult.error(1,"请重新登录");}
            FwAgentRegion agentRegion = agentRegionService.getOne(Wrappers.<FwAgentRegion>lambdaQuery()
                    .eq(FwAgentRegion::getUserId, loginUser.getUser().getUserId())
                    .eq(FwAgentRegion::getAgent, Constant.IsRuleData.AREA_VIP_MONEY_ID)
                    .eq(FwAgentRegion::getIsDefault, 1));
            if (agentRegion == null) {return AjaxResult.error(1,"仅区县代理可以操作特卖商品");}
            //本代理范围是否已存在特卖商品
            FwSpu saleSpu = fwSpuService.getOne(Wrappers.<FwSpu>lambdaQuery()
                    .eq(FwSpu::getIsSale, 1)
                    .eq(FwSpu::getProvince, agentRegion.getProvince())
                    .eq(FwSpu::getCity, agentRegion.getCity())
                    .eq(FwSpu::getArea, agentRegion.getArea()));
            if (saleSpu != null && ! fwSpu.getId().equals(saleSpu.getId())){
                //说明已存在特卖商品 id不等，不是修改，额外加了一个特卖
                    return AjaxResult.error(1,"同地区仅可存在一个特卖商品");
            }

            //填充省市县
            fwSpu.setProvince( agentRegion.getProvince() );
            fwSpu.setCity( agentRegion.getCity() );
            fwSpu.setArea( agentRegion.getArea() );
        }


        //计算消证
        BigDecimal bigDecimal = ruleDatasService.getBigDecimal(Constant.IsRuleData.ONLINE_DISAPPEAR_MAGNIFICATION);
        if (fwSpu.getIsQuiz() != null && fwSpu.getIsQuiz() == 1) {
            fwSpu.setDisappear( fwSpu.getRealPrice() );
        } else {
            fwSpu.setDisappear( fwSpu.getPrice().multiply(bigDecimal) );
        }

        //验证质押商甲
        if (fwSpu.getShopId() != null) {
            if (Integer.valueOf(1).equals(fwSpu.getIsOffline())) {
                shopService.shopPublishSpu(fwSpu.getShopId(),Constant.ShopRuleData.SHOP_SHANGJIA_OFFLINE);
            }else{
                shopService.shopPublishSpu(fwSpu.getShopId(),Constant.ShopRuleData.SHOP_SHANGJIA_ONLINE);
            }
        }


        //图片
        imagesService.remove(Wrappers.<FwImages>lambdaQuery().eq(FwImages::getBusinessId, fwSpu.getId()));
        fwSpu.getImages().forEach(image -> {
            image.setId(idXD.nextId());
            image.setBusinessId( fwSpu.getId() );
            image.setStatus(1);
        } );
        imagesService.saveBatch( fwSpu.getImages() );

        //规格
        fwSpu.setBalance(0L);
        skuService.remove( Wrappers.<FwSku>lambdaQuery().eq(FwSku::getSpuId, fwSpu.getId()) );
        fwSpu.getSkuList().forEach(sku->{
            sku.setId(idXD.nextId() );
            sku.setSpuId( fwSpu.getId() );
            fwSpu.setBalance(fwSpu.getBalance() + sku.getSkuBalance() )  ;
        } );
        skuService.saveBatch( fwSpu.getSkuList() );
        return null;
    }

    /**
     * 删除商品
     */
    @PreAuthorize("@ss.hasPermi('admin:spu:remove')")
    @Log(title = "商品", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return AjaxResult.success(fwSpuService.removeByIds(Arrays.asList(ids)));
    }
}
